import EventEmitter from 'events';
import { Dialog, Loading } from 'quasar';

export default class VoiceRecorder extends EventEmitter {
  recorder: MediaRecorder | null = null;
  voiceData: Array<Blob> = [];
  isRecording = false;
  bitRates = 44100;
  constructor(bitRates = 44100) {
    super();
    if (bitRates && typeof bitRates === 'number') {
      this.bitRates = bitRates;
    }
  }
  start() {
    if (navigator.mediaDevices) {
      navigator.mediaDevices
        .getUserMedia({ audio: true, video: false })
        .then((stream) => {
          if (stream) {
            this.recorder = new MediaRecorder(stream, {
              audioBitsPerSecond: this.bitRates,
            });
            this.startRecoding();
            this.emit('onReady', this.recorder);
          }
        })
        .catch((error) => {
          Dialog.create({
            title: 'Premission Denied Error',
            message: error.message,
          });
          throw error;
        });
    } else {
      Dialog.create({
        title: 'Error',
        message: 'Your Browser does not support Voice Recording',
      });
      throw new Error('Not surpport Voice Recording');
    }
  }
  startRecoding() {
    if (!this.recorder) {
      Dialog.create({
        title: 'Error',
        message: 'Your Browser does not support Voice Recording',
      });
      throw new Error('Not surpport Voice Recording');
    }
    if (this.isRecording) {
      return;
    }
    this.voiceData = [];
    this.recorder?.start(100);
    this.isRecording = true;
    this.recorder.ondataavailable = (event) => {
      this.voiceData.push(event.data);
      this.emit('onData', event.data);
    };
    this.emit('onStart');
  }
  stop() {
    if (this.isRecording) {
      const blob = new Blob(this.voiceData, { type: 'audio/webm;codecs=opus' });
      this.voiceData = [];
      this.recorder?.stop();
      this.isRecording = false;
      this.emit('onStop', blob);
    }
  }
  pause() {
    if (this.isRecording) {
      this.recorder?.pause();
      this.emit('onPause', this.voiceData);
    }
  }
}
